using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using System.IO;

namespace FarmExport
{
    class Program
    {
        StreamWriter sw;
        static void Main(string[] args)
        {
            Program p = new Program();
            p.Start();
        }

        private void Start()
        {
            sw = new StreamWriter("./Farm.xml", false, Encoding.UTF8);
            using (sw)
            {
                SPFarm farm = SPFarm.Local;
                SPWebService service = farm.Services.GetValue<SPWebService>("");

                Print("<Farm>");
                foreach (SPWebApplication webApp in service.WebApplications)
                {
                    Print("<WebApplication Name=\"" + webApp.Name + "\">");
                    GetSiteCollections(webApp);
                    Print("</WebApplication>");
                }
                Print("</Farm>");

                
            }

            Console.WriteLine("Press any key to exit");
            Console.ReadLine();
        }



        private void GetSiteCollections(SPWebApplication webApp)
        {
            SPSiteCollection sites = webApp.Sites;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                foreach (SPSite site in sites)
                {
                    Print("<SiteCollection Url=\"" + site.Url + "\">");
                    GetWebs(site.RootWeb);
                    Print("</SiteCollection>");
                }
            });
        }

        private void GetWebs(SPWeb web)
        {            
            Print("<Web Name=\"" + web.Name + "\" Title=\"" + web.Title + "\">");

            foreach (SPWeb subweb in web.Webs) 
                GetWebs(subweb);
            Print("</Web>");
        }

        private void Print(string p)
        {
            Console.WriteLine(p);
            sw.Write(p);

        }
    }
}
